<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="admin.Connectmysql" %>

<%
    // 安全获取exam_id参数
    int examId = 0;
    try {
        String examIdParam = request.getParameter("exam_id");
        if (examIdParam != null && !examIdParam.trim().isEmpty()) {
            examId = Integer.parseInt(examIdParam);
        } else {
            throw new Exception("缺少exam_id参数");
        }
    } catch (Exception e) {
        out.print("<script>alert('获取考试ID失败: " + e.getMessage() + "'); history.back();</script>");
        return;
    }

    // 安全获取student_id参数
    int studentId = 0;
    try {
        String studentIdParam = request.getParameter("student_id");
        if (studentIdParam != null && !studentIdParam.trim().isEmpty()) {
            studentId = Integer.parseInt(studentIdParam);
        } else {
            throw new Exception("缺少student_id参数");
        }
    } catch (Exception e) {
        out.print("<script>alert('获取学生ID失败: " + e.getMessage() + "'); history.back();</script>");
        return;
    }

    // 数据库连接
    Connectmysql conn = new Connectmysql(
            "jdbc:mysql://localhost:3306/exam",
            "root", "root", "com.mysql.cj.jdbc.Driver");

    if (!conn.open()) {
        out.print("<script>alert('数据库连接失败'); history.back();</script>");
        return;
    }

    // 获取考试题目总数
    int totalQuestions = 0;
    try {
        String countSql = "SELECT COUNT(*) AS total FROM exam_question WHERE exam_id = ?";
        ResultSet countRs = conn.executeSql(countSql, new Object[]{examId});
        if (countRs.next()) {
            totalQuestions = countRs.getInt("total");
        } else {
            throw new Exception("无法获取题目总数");
        }
    } catch (Exception e) {
        out.print("<script>alert('获取题目总数失败: " + e.getMessage() + "'); history.back();</script>");
        return;
    }

    // 获取所有答案
    Map<Integer, String> studentAnswers = new HashMap<>();
    Enumeration<String> paramNames = request.getParameterNames();

    while (paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        if (paramName.startsWith("answer_")) {
            try {
                // 解析问题ID
                String questionIdStr = paramName.substring(7);
                int questionId = Integer.parseInt(questionIdStr);
                String answer = request.getParameter(paramName);

                // 确保答案不为空
                if (answer != null && !answer.trim().isEmpty()) {
                    studentAnswers.put(questionId, answer);
                }
            } catch (NumberFormatException e) {
                // 忽略无效参数
            }
        }
    }

    // 计算分数
    double totalScore = 0;
    int correctCount = 0;
    int unansweredCount = 0;

    try {
        // 获取考试题目和正确答案
        String sql = "SELECT q.question_id, q.correct_answer, q.score " +
                "FROM exam_question eq JOIN question q ON eq.question_id = q.question_id " +
                "WHERE eq.exam_id = ?";
        ResultSet rs = conn.executeSql(sql, new Object[]{examId});

        while (rs.next()) {
            int questionId = rs.getInt("question_id");
            String correctAnswer = rs.getString("correct_answer");
            double questionScore = rs.getDouble("score");

            String studentAnswer = studentAnswers.get(questionId);

            if (studentAnswer != null) {
                if (studentAnswer.equals(correctAnswer)) {
                    totalScore += questionScore;
                    correctCount++;
                }
            } else {
                unansweredCount++;
            }
        }
    } catch (Exception e) {
        out.print("<script>alert('计算分数失败: " + e.getMessage() + "'); history.back();</script>");
        return;
    }

    // 获取课程ID
    int courseId = 0;
    try {
        String sql = "SELECT course_id FROM exam WHERE exam_id = ?";
        ResultSet rs = conn.executeSql(sql, new Object[]{examId});
        if (rs.next()) {
            courseId = rs.getInt("course_id");
        } else {
            throw new Exception("未找到考试信息");
        }
    } catch (Exception e) {
        out.print("<script>alert('获取课程ID失败: " + e.getMessage() + "'); history.back();</script>");
        return;
    }

    // 判断是否通过 (60分及格)
    boolean isPassed = (totalScore >= 60);

    // 存储成绩
    try {
        String sql = "INSERT INTO student_score (student_id, exam_id, course_id, score, is_passed) " +
                "VALUES (?, ?, ?, ?, ?) " +
                "ON DUPLICATE KEY UPDATE score = VALUES(score), is_passed = VALUES(is_passed)";
        int result = conn.executeSqlUpdate(sql, new Object[]{
                studentId, examId, courseId, totalScore, isPassed ? 1 : 0
        });

        if (result <= 0) {
            out.print("<script>alert('成绩保存失败'); history.back();</script>");
            return;
        }
    } catch (Exception e) {
        out.print("<script>alert('成绩保存失败: " + e.getMessage() + "'); history.back();</script>");
        return;
    }

    // 清除session中的考试ID
    session.removeAttribute("currentExamId");
%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>考试结果</title>
    <style>
        .result-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .result-modal.active {
            opacity: 1;
            visibility: visible;
        }

        .result-content {
            background: white;
            border-radius: 12px;
            max-width: 500px;
            width: 100%;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            transform: translateY(-20px);
            opacity: 0;
            transition: all 0.3s ease 0.1s;
        }

        .result-modal.active .result-content {
            transform: translateY(0);
            opacity: 1;
        }

        .result-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f8f9fa;
        }

        .result-body {
            padding: 2rem;
        }

        .result-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1.5rem;
            font-size: 2.5rem;
        }

        .result-icon.success {
            background: rgba(0, 180, 42, 0.1);
            color: #00B42A;
        }

        .result-stats {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            margin: 1.5rem 0;
        }

        .stat-box {
            background: #f9fafb;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            border: 1px solid #e5e7eb;
        }

        .btn-submit {
            background: linear-gradient(135deg, #165DFF 0%, #0E4BC0 100%);
            color: white;
            font-weight: 600;
            padding: 0.8rem 1.8rem;
            border-radius: 10px;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            width: 100%;
            margin-top: 1rem;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(22, 93, 255, 0.3);
        }

        .btn-submit i {
            margin-right: 8px;
        }

        .additional-stats {
            background: #e6f7ff;
            border: 1px solid #91d5ff;
            border-radius: 8px;
            padding: 1rem;
            margin: 1rem 0;
        }

        .additional-stats p {
            display: flex;
            justify-content: space-between;
            margin: 0.5rem 0;
            font-size: 0.95rem;
            color: #003a8c;
        }
    </style>
    <script>
        // 显示结果模态框
        window.onload = function() {
            document.getElementById('total-score').textContent = <%= totalScore %>.toFixed(1);
            document.getElementById('correct-count').textContent = <%= correctCount %>;
            document.getElementById('total-count').textContent = <%= totalQuestions %>;
            document.getElementById('unanswered-count').textContent = <%= unansweredCount %>;
            document.getElementById('passing-score').textContent = '60.0';

            const passStatus = document.getElementById('pass-status');
            if (<%= isPassed %>) {
                passStatus.textContent = '考试通过 ✓';
                passStatus.className = 'px-4 py-2 rounded-full text-lg font-medium bg-green-100 text-green-800';
            } else {
                passStatus.textContent = '考试未通过 ✗';
                passStatus.className = 'px-4 py-2 rounded-full text-lg font-medium bg-red-100 text-red-800';
            }

            document.getElementById('result-modal').classList.add('active');
        }
    </script>
</head>
<body>
<div id="result-modal" class="result-modal active">
    <div class="result-content">
        <div class="result-header">
            <h3 class="text-xl font-bold text-gray-900">考试结果</h3>
            <button id="close-modal" class="text-gray-400 hover:text-gray-500" onclick="window.location.href='student.jsp#grades'">
                <i class="fa fa-times"></i>
            </button>
        </div>

        <div class="result-body">
            <div class="result-icon success">
                <i class="fa fa-check"></i>
            </div>
            <h4 class="text-2xl font-bold text-center mb-4">考试提交成功！</h4>
            <p class="text-gray-600 text-center mb-6">以下是您的考试结果：</p>

            <div class="result-stats">
                <div class="stat-box">
                    <p class="text-sm text-gray-500">总分</p>
                    <p class="text-2xl font-bold text-blue-600" id="total-score">0</p>
                </div>
                <div class="stat-box">
                    <p class="text-sm text-gray-500">及格分数</p>
                    <p class="text-2xl font-bold text-gray-800" id="passing-score">60.0</p>
                </div>
                <div class="stat-box">
                    <p class="text-sm text-gray-500">答对题数</p>
                    <p class="text-2xl font-bold text-gray-900" id="correct-count">0</p>
                </div>
                <div class="stat-box">
                    <p class="text-sm text-gray-500">总题数</p>
                    <p class="text-2xl font-bold text-gray-900" id="total-count">0</p>
                </div>
            </div>

            <div class="additional-stats">
                <p>
                    <span>未答题数：</span>
                    <strong><span id="unanswered-count">0</span></strong>
                </p>
                <p>
                    <span>题目完成度：</span>
                    <strong><%= Math.round(100.0 * (totalQuestions - unansweredCount) / totalQuestions) %>%</strong>
                </p>
                <p>
                    <span>正确率：</span>
                    <strong><%= totalQuestions > 0 ? Math.round(100.0 * correctCount / totalQuestions) : 0 %>%</strong>
                </p>
            </div>

            <div class="mb-4 text-center">
                <span class="px-4 py-2 rounded-full text-lg font-medium" id="pass-status"></span>
            </div>

            <button id="btn-review" class="btn-submit" onclick="window.location.href='student.jsp#grades'">
                <i class="fa fa-bar-chart"></i>查看成绩详情
            </button>
        </div>
    </div>
</div>
</body>
</html>